package org.sakai.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.sakai.service.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("/public")
public class PublicController {

    @Autowired
    private MinioService minioService;

    @RequestMapping("/images/{id}")
    public void downloadImage(@PathVariable("id") String id, HttpServletResponse response) {
        try {
            // 获取文件流并写入响应
            InputStream fileStream = minioService.getFileAsStream(id);
            if (fileStream != null) {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + id);
                int bufferSize = Math.min(8192, (int) Math.max(fileStream.available(), 1024));
                byte[] buffer = new byte[bufferSize];
                int bytesRead;
                while ((bytesRead = fileStream.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
                fileStream.close();
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            }
        } catch (Exception e) {
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred");
            } catch (IOException ioEx) {
                ioEx.printStackTrace();
            }
            e.printStackTrace();
        }
    }
}
